package com.chaodows.commons.util.qrcode;

import com.google.zxing.LuminanceSource;


import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

/**
 *
 * ============================
 *
 * @Author pengzhichao
 * @Description //TUDO $
 * @Date 2021/8/4 15:30
 * @Version 1.0
 * ============================
 **/
public class BufferedImageLuminanceSource extends LuminanceSource {

    private final BufferedImage image;
    private final int left;
    private final int top;


    public BufferedImageLuminanceSource(BufferedImage image){
        this(image.getWidth(),image.getHeight(),image,0,0);
    }

    public BufferedImageLuminanceSource(int width, int height, BufferedImage image, int left, int top) {
        super(width, height);
        this.image = image;
        this.left = left;
        this.top = top;
    }

    @Override
    public byte[] getRow(int i, byte[] bytes) {
        if (i < 0 || i >= getHeight()) {
            throw new IllegalArgumentException("Requested row is outside the image: " + i);
        }
        int width = getWidth();
        if (bytes == null || bytes.length < width) {
            bytes = new byte[width];
        }
        image.getRaster().getDataElements(left, top + i, width, 1, bytes);
        return bytes;
    }

    @Override
    public byte[] getMatrix() {
        int width = getWidth();
        int height = getHeight();
        int area = width * height;
        byte[] matrix = new byte[area];
        image.getRaster().getDataElements(left, top, width, height, matrix);
        return matrix;
    }

    @Override
    public boolean isCropSupported() {
        return true;
    }

    @Override
    public LuminanceSource rotateCounterClockwise() {
        int sourceWidth = image.getWidth();
        int sourceHeight = image.getHeight();
        AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
        BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
        Graphics2D g = rotatedImage.createGraphics();
        g.drawImage(image, transform, null);
        g.dispose();
        int width = getWidth();
        return new BufferedImageLuminanceSource(getHeight(),width,rotatedImage, top,sourceWidth - (left - width));
//                                              BufferedImage image, int left, int top, int width, int height
    }

}
